package com.kele.goods.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kele.common.model.response.PageResult;
import com.kele.goods.mapper.TypeTemplateMapper;
import com.kele.model.goods.Brand;
import com.kele.model.goods.TypeTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class TypeTemplateService {

    @Autowired
    private TypeTemplateMapper typeTemplateMapper;

    public List<TypeTemplate> findAll() {
        return typeTemplateMapper.selectList(Wrappers.emptyWrapper());
    }

    /**
     * @param page 页码
     * @param size 每页大小
     * @param searchMap 查询条件 key:name firstChar
     * @return
     */
    public PageResult<TypeTemplate> findPage(int page, int size,Map searchMap) {
        //构造查询条件
        QueryWrapper<TypeTemplate> queryWrapper = createQueryWrapper(searchMap);

        Page<Brand> pageList = typeTemplateMapper.selectPage(new Page(page,size), queryWrapper);
        //构造PageResult对象
        PageResult<TypeTemplate> result = new PageResult(pageList.getTotal(),pageList.getRecords());
        return result;
    }


    private QueryWrapper<TypeTemplate> createQueryWrapper(Map searchMap){
        //1 构造查询条件
        QueryWrapper<TypeTemplate> queryWrapper = new QueryWrapper();//where ?1 = XX
        // select name first_char from tb_brand where name like '%XXX%' and first_char ='XX'
        if(searchMap!=null) {
            if (searchMap.get("name") != null && !searchMap.get("name").equals("")) {
                queryWrapper.lambda().like(TypeTemplate::getName, searchMap.get("name"));
            }
        }
        return queryWrapper;
    }

    /**
     * 根据ID 查询
     * @param id
     * @return
     */
    public TypeTemplate findById(Long id) {
        return typeTemplateMapper.selectById(id);
    }

    /**
     * 新增
     * @param typeTemplate
     */
    public void add(TypeTemplate typeTemplate) {
        typeTemplateMapper.insert(typeTemplate);
    }

    /**
     * 修改
     * @param typeTemplate
     */
    public void update(TypeTemplate typeTemplate) {
        typeTemplateMapper.updateById(typeTemplate);
    }

    /**
     * 根据ID删除
     * @param id
     */
    public void delete(Long id) {
        typeTemplateMapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteByIds(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        typeTemplateMapper.deleteBatchIds(idList);
    }
}
